package com.ljfiction.book.activitys;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.BookCommentBean;
import com.ljfiction.book.Baner.ShupingHuifuBean;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.ShupingHuifuAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.SoftHideKeyBoardUtil;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class ShupingDatasActivity extends BaseActivity {
    @BindView(R.id.back_shupingdatas)
    ImageView backShupingdatas;
    @BindView(R.id.huifu_shupingdatas)
    RecyclerView huifuShupingdatas;
    @BindView(R.id.tocommenthuifushuping)
    ContainsEmojiEditText tocommenthuifushuping;
    @BindView(R.id.sendhuifushuping)
    TextView sendhuifushuping;
    @BindView(R.id.refresh_authshuping)
    SmartRefreshLayout refreshAuthshuping;
    @BindView(R.id.top_shupingdatas)
    LinearLayout topShupingdatas;
    private BookCommentBean.DataBean.ListBean thisshuping;
    private int page = 1;
    private ShupingHuifuBean shupinghuifu;
    private List<ShupingHuifuBean.DataBean.ListBean> huifulist = new ArrayList<>();
    private ShupingHuifuAdapter adpter;
    private Intent intent;
    private ViewHolder viewHolder;
    private Context context;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shuping_datas);
        ButterKnife.bind(this);
        SoftHideKeyBoardUtil.assistActivity(this);
        intent = new Intent(this, UserCenterActivity.class);
        topShupingdatas.getBackground().setAlpha(255);
        context = this;
        thisshuping = (BookCommentBean.DataBean.ListBean) getIntent().getSerializableExtra("thisshuping");
        if (thisshuping == null) {
            id = getIntent().getStringExtra("id");
            intTodata();
        } else {
            id = String.valueOf(thisshuping.getId());
            intView();
        }
    }

    private void intTodata() {
        OkHttpUtils.post(HttpManager.IP + "/comm-getcomminfo")

                .params("id", id)
                .params("type", "0")
                .params("startPage", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson g = new Gson();
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                thisshuping = g.fromJson(js.getString("data"), BookCommentBean.DataBean.ListBean.class);
                                intView();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    private void intData() {
        OkHttpUtils.post(HttpManager.IP + "/comm-replyInfo")

                .params("commentid", id)
                .params("startPage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        refreshAuthshuping.finishLoadMore();
                        refreshAuthshuping.finishRefresh();
                        Gson gson = new Gson();
                        try {
                            shupinghuifu = gson.fromJson(s, ShupingHuifuBean.class);
                            if (shupinghuifu.getReturnCode() == 200) {
                                huifulist.addAll(shupinghuifu.getData().getList());
                                viewHolder.numShupingdatas.setText("共" + huifulist.size() + "条");
                            } else {

                            }
                            adpter.notifyDataSetChanged();
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void intView() {
        intData();
        adpter = new ShupingHuifuAdapter(R.layout.huifushuping_item, huifulist);
        huifuShupingdatas.setAdapter(adpter);
        huifuShupingdatas.setLayoutManager(new LinearLayoutManager(this));
        huifuShupingdatas.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        View headerView = getLayoutInflater().inflate(R.layout.headshupingview, null);
        headerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        viewHolder = new ViewHolder(headerView);
        viewHolder.booknameMyshupingdatas.setText("《" + thisshuping.getBookName() + "》");
        viewHolder.nameMyshupingdatas.setText(thisshuping.getPseudonym());
        Glide.with(this).load(thisshuping.getUserHeadPortraitURL()).override(ScreenUtils.getNum(ShupingDatasActivity.this,52), ScreenUtils.getNum(ShupingDatasActivity.this,52)).into(viewHolder.imageMyshupingdatas);
        viewHolder.contentMyshupingdatas.setText(thisshuping.getCommentContext());
        viewHolder.timeMyshupingdatas.setText(TimeTool.getTimeAndChange(String.valueOf(thisshuping.getCommentDateTime())));
        viewHolder.selectnumMyshupingdatas.setText(String.valueOf(thisshuping.getThumbsCount()));
        viewHolder.pinglunnumMyshupingdatas.setText(String.valueOf(thisshuping.getReplyCount()));
        if (thisshuping.getIsthumbs() == 1) {
            viewHolder.dianzanimageMyshupingdatas.setImageResource(R.mipmap.good);
        } else {
            viewHolder.dianzanimageMyshupingdatas.setImageResource(R.mipmap.goodno);
        }
        viewHolder.dengjiMyshupingdatas.setText("LV" + thisshuping.getUserGrade());
        if (thisshuping.getUserSex() == 0) {
            viewHolder.sexMyshupingdatas.setImageResource(R.drawable.sex_n);
        } else {
            viewHolder.sexMyshupingdatas.setImageResource(R.mipmap.sex_v);
        }
        if (thisshuping.getVipGrade() > 0) {
            viewHolder.isvipMyshupingdatas.setVisibility(View.VISIBLE);
        } else {
            viewHolder.isvipMyshupingdatas.setVisibility(View.GONE);
        }
        viewHolder.dianzanimageMyshupingdatas.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManageBean.isLogin(ShupingDatasActivity.this)) {
                    return;
                }
                OkHttpUtils.post(HttpManager.IP + "/comm-GiveThumbs")

                        .params("commentId", String.valueOf(thisshuping.getId()))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(s);
                                    if (jsonObject.getInt("returnCode") == 200) {
                                        if (thisshuping.getIsthumbs() == 0) {
                                            thisshuping.setIsthumbs(1);
                                            thisshuping.setThumbsCount(thisshuping.getThumbsCount() + 1);
                                            viewHolder.dianzanimageMyshupingdatas.setImageResource(R.mipmap.good);
                                        } else {
                                            thisshuping.setIsthumbs(0);
                                            thisshuping.setThumbsCount(thisshuping.getThumbsCount() - 1);
                                            viewHolder.dianzanimageMyshupingdatas.setImageResource(R.mipmap.goodno);
                                        }
                                        viewHolder.selectnumMyshupingdatas.setText(String.valueOf(thisshuping.getThumbsCount()));
                                        viewHolder.pinglunnumMyshupingdatas.setText(String.valueOf(thisshuping.getReplyCount()));
                                    }else if (jsonObject.getInt("returnCode") == 400){
                                        Intent intent=new Intent(context, LoginActivity.class);
                                        startActivity(intent);
                                        showToast(jsonObject.getString("msg"));
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });

            }
        });
        viewHolder.imageMyshupingdatas.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.putExtra("userId", String.valueOf(thisshuping.getUserId()));
                startActivity(intent);
            }
        });
        adpter.addHeaderView(headerView);
        adpter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                intent.putExtra("userId", String.valueOf(huifulist.get(position).getUserId()));
                startActivity(intent);
            }
        });
        refreshAuthshuping.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                intData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                huifulist.clear();
                page = 1;
                intData();
            }
        });
        tocommenthuifushuping.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (String.valueOf(editable).length() >= 100) {
                    showToast("评论内容不能超过100个字");
                }
            }
        });
    }

    @OnClick({R.id.back_shupingdatas, R.id.sendhuifushuping})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_shupingdatas:
                goBack();
                break;
            case R.id.sendhuifushuping:
                if (!UserManageBean.isLogin(ShupingDatasActivity.this)) {
                    return;
                }
                if (tocommenthuifushuping.getText().toString().equals("")) {
                    showToast("评论不能为空哦");
                    return;
                }
                OkHttpUtils.post(HttpManager.IP + "/add-replyInfo")

                        .params("bookid", String.valueOf(thisshuping.getBookId()))
                        .params("replyCommentsContent", tocommenthuifushuping.getText().toString())
                        .params("userName", UserManageBean.userBean.getPseudonym())
                        .params("bookName", thisshuping.getBookName())
                        .params("commentId", String.valueOf(thisshuping.getId()))
                        .params("puserId", String.valueOf(thisshuping.getUserId()))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(s);
                                    if (jsonObject.getInt("returnCode") == 200) {
                                        showToast(jsonObject.getString("msg"));
                                        huifulist.clear();
                                        page = 1;
                                        intData();
                                        tocommenthuifushuping.setText("");
                                        thisshuping.setReplyCount(thisshuping.getReplyCount()+1);
                                        viewHolder.pinglunnumMyshupingdatas.setText(String.valueOf(thisshuping.getReplyCount()));
                                        Tool.hideKeybard(ShupingDatasActivity.this);
                                    } else {
                                        if (jsonObject.getInt("returnCode") == 400){
                                            Intent intent=new Intent(ShupingDatasActivity.this,LoginActivity.class);
                                            startActivity(intent);
                                        }
                                        showToast(jsonObject.getString("msg"));
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                break;
        }
    }

    static class ViewHolder {
        @BindView(R.id.image_myshupingdatas)
        CircularImageView imageMyshupingdatas;
        @BindView(R.id.isvip_myshupingdatas)
        ImageView isvipMyshupingdatas;
        @BindView(R.id.name_myshupingdatas)
        TextView nameMyshupingdatas;
        @BindView(R.id.sex_myshupingdatas)
        ImageView sexMyshupingdatas;
        @BindView(R.id.dengji_myshupingdatas)
        SuperButton dengjiMyshupingdatas;
        @BindView(R.id.time_myshupingdatas)
        TextView timeMyshupingdatas;
        @BindView(R.id.bookname_myshupingdatas)
        TextView booknameMyshupingdatas;
        @BindView(R.id.content_myshupingdatas)
        TextView contentMyshupingdatas;
        @BindView(R.id.selectnum_myshupingdatas)
        TextView selectnumMyshupingdatas;
        @BindView(R.id.dianzanimage_myshupingdatas)
        ImageView dianzanimageMyshupingdatas;
        @BindView(R.id.pinglunnum_myshupingdatas)
        TextView pinglunnumMyshupingdatas;
        @BindView(R.id.num_shupingdatas)
        TextView numShupingdatas;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
